﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Mayn.Video
{
    public class GlobalKeyboardHook
    {
        // 定义 Windows API 函数
        [DllImport("user32.dll")]
        private static extern IntPtr SetWindowsHookEx(int idHook, KeyboardHookProc lpfn, IntPtr hMod, uint dwThreadId);
        [DllImport("user32.dll")]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);
        [DllImport("user32.dll")]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        // 定义键盘事件委托
        private delegate IntPtr KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam);
        private KeyboardHookProc _hookProc;

        // 定义键盘事件 ID 和句柄
        private const int WH_KEYBOARD_LL = 13;
        private IntPtr _hookHandle = IntPtr.Zero;

        // 定义 End 键的键码
        private const int VK_END = 0x23;

        // 定义事件
        public event EventHandler EndKeyPressed;

        // 构造函数
        public GlobalKeyboardHook()
        {
            _hookProc = KeyboardHookCallback;
        }

        // 安装键盘钩子
        public void InstallHook()
        {
            _hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, IntPtr.Zero, 0);
        }

        // 卸载键盘钩子
        public void UninstallHook()
        {
            UnhookWindowsHookEx(_hookHandle);
        }

        // 键盘事件回调函数
        private IntPtr KeyboardHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)0x100)
            {
                // 检测按下的键盘按键是否为 End 键
                int vkCode = Marshal.ReadInt32(lParam);
                if (vkCode == VK_END)
                {
                    // 触发 EndKeyPressed 事件
                    EndKeyPressed?.Invoke(this, EventArgs.Empty);
                }
            }
            return CallNextHookEx(_hookHandle, nCode, wParam, lParam);
        }
    }
}
